﻿// jQuery zepto vue angular 等库皆有 progress 的实现 以jQuery为例：
layui.use(['form', 'layer', 'jquery'], function () {
    var form = layui.form,
        layer = parent.layer === undefined ? layui.layer : top.layer,
        $ = layui.jquery;

    var $key = $('#key');  // file name    eg: the file is image.jpg,but $key='a.jpg', you will upload the file named 'a.jpg'
    var $userfile = $('#userfile');  // the file you selected

    //var domain = "http://storage.yunspace.com.cn/";
    var domain = "http://dns.qsgjlive.com/";
    // upload info
    var $selectedFile = $('.selected-file');
    var $progress = $(".progress");
    var $uploadedResult = $('.uploaded-result');
    var loading = undefined;

    $("#userfile").change(function () {  // you can ues 'onchange' here to uplpad automatically after select a file
        $uploadedResult.html('');
        
        var selectedFile = $userfile.val();
        if (selectedFile) {
            loading = layer.load(0, {
                shade: false,
                time: 2 * 1000
            });
            var files = selectedFile.replace(/\\/, "|").replace(/\\/, "|").split("|");
            // randomly generate the final file name
            var ramdomName = Math.random().toString(36).substr(2) + $userfile.val().match(/\.?[^.\/]+$/);
            if ($("#userfilename").val() != "") {
                ramdomName = $("#userfilename").val() + files[files.length - 1];
            }
            $key.val(ramdomName);
            $selectedFile.html('文件：' + selectedFile);
            $("#userfilename").val(files[files.length - 1]);
        } else {
            return false;
        }
        var f = new FormData(document.getElementById("testform"));

        $.ajax({
            //url: 'http://upload.qiniu.com/',  // Different bucket zone has different upload url, you can get right url by the browser error massage when uploading a file with wrong upload url.
            url: 'https://up-z2.qiniup.com/', 
            type: 'POST',
            data: f,
            processData: false,
            contentType: false,
            xhr: function () {
                myXhr = $.ajaxSettings.xhr();
                if (myXhr.upload) {
                    myXhr.upload.addEventListener('progress', function (e) {
                        if (e.lengthComputable) {
                            var percent = e.loaded / e.total * 100;
                            $progress.html('上传：' + e.loaded + "/" + e.total + " bytes. " + percent.toFixed(2) + "%");
                        }
                    }, false);
                }
                return myXhr;
            },
            success: function (res) {
                //var str = '<span>已上传：' + res.key + '</span>';
                if (res.key && res.key.match(/\.(jpg|jpeg|png|gif)$/)) {
                    //str += '<img src="' + domain + res.key + '"/>';
                    var id = parseInt($("#imagesPanel span:last").attr("value") || 0) + 1;
                    var html = '<span value="' + id + '" style="position:relative; top: 0;">';
                    html += '<a href="' + domain + res.key + '" target="_bank"><img src="' + domain + res.key + '" style="width: 100px;" /></a>';
                    html += '<button type="button" class="layui-btn layui-btn-sm updateAuditImage" value="' + id + '" style="position:absolute; right: 0;">X</button>';
                    html += '</span>';
                    $("#imagesPanel").append(html);
                    var currentImagesVal = $("#UploadImages").val();
                    var imagesVal = (currentImagesVal ? currentImagesVal + "," : "") + res.key;
                    $("#UploadImages").val(imagesVal);
                }
                //$("#userfilepath").val(domain + res.key);
                //$uploadedResult.html(str);
                layer.msg("文件上传成功！", "success");
                layer.close(loading);
            },
            error: function (res) {
                //console.log("失败:" + JSON.stringify(res));
                var messages = eval("(" + res.responseText + ")");
                if (messages.error == "file exists") {
                    layer.msg('上传失败：有重名文件,请修改文件名后再次上传！', "error");
                } else {
                    layer.msg('上传失败：' + res.responseText, "error");
                }
                layer.close(loading);
            }
        });
        return false;
    });
});